package com.example.test_event_and_callback.infras.async;

import cn.hutool.extra.spring.SpringUtil;

import java.lang.invoke.MethodHandle;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.stream.Collectors;

public class ProviderProcessorMethodHandle extends AsyncProviderProcessor<MethodHandle> {

    public ProviderProcessorMethodHandle(Class<?> demanderClass) {
        super(demanderClass);
    }

    @Override
    void loadProviderMethodMap(Map<String, Method> mappedMethodByParam) {
        providerMethodMap = mappedMethodByParam.entrySet()
                .stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey, // key 保持不变
                        entry -> MethodExchange.toMethodHandle(entry.getValue()) // 将 Method 转换为 MethodHandle
                ));
    }

    @Override
    void putMethodToMap( Map<String, MethodHandle> map, String paramName, Method method) {
        Object bean = SpringUtil.getBean(method.getDeclaringClass());
        MethodHandle methodHandle;
        try {
            // 转换Method为MethodHandle
            methodHandle = MethodExchange.toMethodHandle(method).bindTo(bean);
        } catch (Exception e) {
            // 处理MethodHandle转换异常
            throw new RuntimeException("转换MethodHandle失败", e);
        }
        map.put(paramName, methodHandle);
    }

    @Override
    Demander proxyDataDemander(Object demander) {
        return new AsyncDemanderProxy(demander);
    }

    @Override
    Object executeProviderMethod(Object method, Object provider, String s) {
        try {
            return ((MethodHandle) method).invoke(provider,s);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }


}
